package handlers

import (
	"encoding/json"
	"net/http"
	"order-validation-api/models"
	"order-validation-api/services"
)

// OrderHandler 订单处理器
type OrderHandler struct {
	validationService *services.OrderValidationService
}

// NewOrderHandler 创建新的订单处理器
func NewOrderHandler(validationService *services.OrderValidationService) *OrderHandler {
	return &OrderHandler{
		validationService: validationService,
	}
}

// ValidateOrderRequest 验证订单请求结构
type ValidateOrderRequest struct {
	Order *models.Order `json:"order"`
}

// ValidateOrderResponse 验证订单响应结构
type ValidateOrderResponse struct {
	IsValid bool   `json:"isValid"`
	Error   string `json:"error,omitempty"`
}

// ValidateOrderBatchRequest 批量验证订单请求结构
type ValidateOrderBatchRequest struct {
	Orders []*models.Order `json:"orders"`
}

// ValidateOrderBatchResponse 批量验证订单响应结构
type ValidateOrderBatchResponse struct {
	Results map[string]*ValidateOrderResponse `json:"results"`
}

// SupportedClientsResponse 支持的客户端响应结构
type SupportedClientsResponse struct {
	Clients []string `json:"clients"`
}

// HealthResponse 健康检查响应结构
type HealthResponse struct {
	Status string `json:"status"`
}

// ValidateOrder 验证单个订单
func (h *OrderHandler) ValidateOrder(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	var req ValidateOrderRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, "Invalid JSON", http.StatusBadRequest)
		return
	}

	if req.Order == nil {
		http.Error(w, "Order is required", http.StatusBadRequest)
		return
	}

	err := h.validationService.ValidateOrder(req.Order)
	response := ValidateOrderResponse{
		IsValid: err == nil,
	}
	if err != nil {
		response.Error = err.Error()
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(response)
}

// ValidateOrderBatch 批量验证订单
func (h *OrderHandler) ValidateOrderBatch(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	var req ValidateOrderBatchRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		http.Error(w, "Invalid JSON", http.StatusBadRequest)
		return
	}

	if len(req.Orders) == 0 {
		http.Error(w, "Orders are required", http.StatusBadRequest)
		return
	}

	results := h.validationService.ValidateOrderBatch(req.Orders)
	response := ValidateOrderBatchResponse{
		Results: make(map[string]*ValidateOrderResponse),
	}

	for orderID, err := range results {
		response.Results[orderID] = &ValidateOrderResponse{
			IsValid: err == nil,
		}
		if err != nil {
			response.Results[orderID].Error = err.Error()
		}
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(response)
}

// GetSupportedClients 获取支持的客户端类型
func (h *OrderHandler) GetSupportedClients(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	clients := h.validationService.GetSupportedClients()
	response := SupportedClientsResponse{
		Clients: clients,
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(response)
}

// Health 健康检查
func (h *OrderHandler) Health(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	response := HealthResponse{
		Status: "OK",
	}

	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(response)
}